<?php
/**
 * Created by IntelliJ IDEA.
 * User: wanglu
 * Date: 2017/9/5
 * Time: 11:05
 */

/**
 * Created by wanglu on 2017/9/5.
 */
class User_service extends MY_Service
{


    public function __construct()
    {
        parent::__construct();
        $this->load->model('user_model');
    }

    public function get_user_by_name($name) {
        return   $this->user_model->getRecord(array('username' => $name));
    }

    public function get_user_by_id($id) {
        return  $this->user_model->getRecord(array('id' => $id));
    }


    public function get_users($start, $length, $username, $order_by_createtime)
    {
        if (!empty($username)) {
            $this->db->like('username', $username);
        }
        $orderby = array("createtime" => $order_by_createtime);
        return $this->user_model->getPageData($start, $length, $orderby);
    }

    public function delete_user_by_id($id) {
        return $this->user_model->deleteRecord(array('id'=> $id));
    }

    public function update_password($id, $oldpassword, $newpassword) {
        $user =   $this->user_model->getRecord(array('id' => $id));

        if ($user['pwd'] != $oldpassword) {
            throw  new AppException(ErrorCode::FAIL, " old password is wrong ,change fail!");
        }

        return $this->user_model->updateRecord(array('pwd'=> $newpassword), array('id'=> $id));
    }


    public function add_or_update_user($username, $pwd, $role, $email, $id = 0)
    {

        if (empty($id)) {
            $dbUser = $this->user_model->getRecord(array('username' => $username));
            if (!empty($dbUser)) {
                throw  new AppException(ErrorCode::USER_NAME_EXITS, " add User fail, The user has already existed!");
            }

            $user = array(
                'username' => $username,
                'pwd' => $pwd,
                'email' => $email,
                'role' => $role,
                'createtime' => time(),
            );


            return $this->user_model->createRecord($user);

        } else {
            $idUser = $this->user_model->getRecord(array('id' => $id));
            if ($idUser['username'] != $username) {
                //修改了用户名
                $dbUser = $this->user_model->getRecord(array('username' => $username));
                if (!empty($dbUser)) {
                    throw  new AppException(ErrorCode::USER_NAME_EXITS, " edit User fail, The user has already existed!");
                }
            }

            $user = array(
                'username' => $username,
                'pwd' => $pwd,
                'email' => $email,
                'role' => $role
            );
            return $this->user_model->updateRecord($user, array('id'=> $id));
        }
    }

}